package com.guandeng.mall.portal.service.impl;

import com.guandeng.mall.api.HelloService;
import com.guandeng.mall.common.exception.Asserts;
import com.guandeng.mall.mapper.UmsMemberMapper;
import com.guandeng.mall.model.UmsMember;
import com.guandeng.mall.model.UmsMemberExample;
import com.guandeng.mall.portal.service.MemberCacheService;
import com.guandeng.mall.portal.service.MemberService;
import io.netty.util.internal.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.security.core.AuthenticationException;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;


@Service
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberCacheService memberCacheService;

    @Resource
    private UmsMemberMapper memberMapper;

    @org.apache.dubbo.config.annotation.Reference
    private HelloService helloService;

    @Override
    public void register(String username, String password, String telphone, String authCode) {
        if (!verifyAuthCode(telphone, authCode)) {
            Asserts.fail("验证码错误");
        }
        // 查询用户是否存在

    }

    @Override
    public UmsMember getMember(String username) {
        UmsMember umsMember = memberCacheService.getMember(username);
        return umsMember;
    }

    @Override
    public String login(String username, String password) {

        String token = null;
        try {

        } catch (AuthenticationException $e) {

        }
        return token;
    }

    @Override
    public String loadUserByUsername(String username) {
        return "test";
    }

    @Override
    public UmsMember getByUsername(String username) {
        UmsMember umsMember = memberCacheService.getMember(username);
        if (umsMember != null) {
            return umsMember;
        }
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(memberList)) {
            UmsMember member = memberList.get(0);
            memberCacheService.setMember(member);
            return member;
        }
        return null;
    }

    // 验证码校验
    private boolean verifyAuthCode(String telphone, String authCode) {
        if (StringUtils.isEmpty(authCode)) {
            return false;
        }
        String realAuthCode = memberCacheService.getAuthCode(telphone);
        return realAuthCode.equals(authCode);
    }

    @Override
    public String generateAuthCode(String telphone) {
        return "test";
    }

    @Override
    public String dubbo(){
        return helloService.hello("test");
    }
}
